<?php

namespace app\admin\controller;

use app\admin\model\Version as VersionModel;
use app\admin\service\OssService;
use app\admin\validate\VersionValidate;
use app\admin\validate\CommonnValidate;
use app\BaseController;

class Version extends BaseController
{
    protected $middleware = ['Auth'];

    public function list() {
        $params = $this->request->post(['current', 'size', 'updateType']);
        $validate = new CommonnValidate();
        if (!$validate->scene('list')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new VersionModel();
        $whereArr = [];
        if(isset($params['updateType']) && $params['updateType']) {
            $whereArr[] = ["updateType", "=", $params['updateType']];
        }
        $list = $sql
            ->where($whereArr)
            ->order('create_at desc')
            ->paginate([
                'list_rows'=> request()->param('size'),
                'page' => request()->param('current'),
            ]);
        return result()->success($list);
    }

    public function detail()
    {
        $params = $this->request->post(['id']);
        $sql = new VersionModel();
        $info = $sql->where('id', $params['id'])->find();
        $oss = new OssService();
        $info['downloadUrl'] = $oss->signId($info['fileId']);
        return result()->success($info);
    }

    public function addEdit() {
        $params = $this->request->post(['id']);
        if(isset($params['id']) && $params['id']) {
            return $this->edit();
        }
        return $this->add();
    }

    public function add() {
        $params = $this->request->post(['versionCode', 'versionName', 'versionInfo', 'updateType', 'fileId']);
        $validate = new VersionValidate();
        if (!$validate->scene('add')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new VersionModel();
        $sql->save($params);
        return result()->success("添加成功");
    }

    public function edit() {
        $params = $this->request->post(['id', 'versionCode', 'versionName', 'versionInfo', 'updateType', 'fileId']);
        $validate = new CommonnValidate();
        if (!$validate->scene('edit')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new VersionModel();
        $info = $sql->find($params['id']);
        $info->save($params);
        return result()->success("修改成功");
    }

    public function dels() {
        $params = $this->request->post(['ids']);
        $validate = new CommonnValidate();
        if (!$validate->scene('dels')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new VersionModel();
        $sql->destroy($params['ids']);
        return result()->success("删除成功");
    }
}